package com.tonglin.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tonglin.eduservice.EduApplication;
import com.tonglin.eduservice.entity.EduSubject;
import com.tonglin.eduservice.entity.excel.SubjectData;
import com.tonglin.eduservice.entity.subject.OneSubject;
import com.tonglin.eduservice.entity.subject.TwoSubject;
import com.tonglin.eduservice.listener.SubjectExcelListener;
import com.tonglin.eduservice.mapper.EduSubjectMapper;
import com.tonglin.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jdk.internal.util.xml.impl.Input;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author tonglin
 * @since 2021-05-09
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Autowired
    EduSubjectMapper eduSubjectMapper;
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {

        try {
            //文件输入流
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        }catch (Exception e){
                e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //首先查询所有一级分类
        //然后根据一级分类的id查询所有二级分类
        //最后把一级和二级分类封装到List集合中
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id","0");
        List<EduSubject> list = eduSubjectMapper.selectList(queryWrapper);
        List<OneSubject> list1 = new ArrayList<>();
        for (EduSubject es: list) {
            OneSubject oneSubject = new OneSubject();
            oneSubject.setId(es.getId());
            oneSubject.setTitle(es.getTitle());
            oneSubject.setChildren(getAllTwoSubject(es.getId()));
            list1.add(oneSubject);

        }

        return list1;
    }
    //根据父id查询二级分类，返回二级分类列表
    public List<TwoSubject> getAllTwoSubject(String parentId){
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",parentId);
        List<EduSubject> list = eduSubjectMapper.selectList(queryWrapper);
        List<TwoSubject> list1 = new ArrayList<>();
        for (EduSubject es: list) {
            TwoSubject twoSubject = new TwoSubject();
            twoSubject.setId(es.getId());
            twoSubject.setTitle(es.getTitle());
            list1.add(twoSubject);
        }

        return list1;
    }
}
